package com.ulic.customerManApplication.usermodule.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Component;

import com.ulic.customerManApplication.base.BaseDao;
import com.ulic.customerManApplication.usermodule.bo.Role;
import com.ulic.customerManApplication.usermodule.bo.User;
import com.ulic.customerManApplication.usermodule.bo.UserRole;
import com.ulic.customerManApplication.usermodule.dao.RoleDao;

@Component("userRoleDao")
public class RoleDaoImpl extends BaseDao implements RoleDao {

	@Override
	public Role getRole(int oid) throws Exception {
		return (Role)hibernateTemplate.get(Role.class, oid);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Role> getRole() throws Exception {
		return hibernateTemplate.find("from Role order by oid");
	}

	@SuppressWarnings("unchecked")
	@Override
	public void setUserRole(String userid, int objectid) throws Exception {
		//删除原有角色
		String hql = "from UserRole r where r.user = ?";
		Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
		Query q = session.createQuery(hql);
		q.setParameter(0, userid);
		List<UserRole> list =q.list();
		for (UserRole userrole : list) {
			hibernateTemplate.delete(userrole);
		}
		//添加新的角色
		UserRole ur = new UserRole();
		ur.setObjectid(objectid);
		User user = (User)hibernateTemplate.load(User.class, userid);
		ur.setUser(user);
		hibernateTemplate.save(ur);
	}

	@SuppressWarnings("unchecked")
	@Override
	public int[] getUserRole(String userid) throws Exception {
		String hql = "from UserRole r where r.user = "+Integer.parseInt(userid);
		List<UserRole> list = hibernateTemplate.find(hql);
		int[] objectids = new int[(list.size())];
		for (int i = 0; i < list.size(); i++) {
			objectids[i] = list.get(i).getObjectid();
		}
		return objectids;
	}

}
